//
//  HomeTableViewController.swift
//  CXCWeibo
//
//  Created by cxc on 15/6/24.
//  Copyright © 2015年 china. All rights reserved.
//

import UIKit
import SVProgressHUD

class HomeTableViewController: BaseTableViewController,StatusCellDelegate {

    /**
      *表格绑定的微博数据数组
    */
    var statusesList:[Status]?{
        didSet{
            tableView.reloadData()
            refreshControl?.endRefreshing()
        }
    }
    
    lazy var rowHeightCache = [Int:CGFloat]()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        visitorView?.setupViewInfo("visitordiscover_feed_image_house", message: "关注一些人，回这里看看有什么惊喜", isHome: true)
        if !userLogin{
            return
        }
        
        setupNavigationBar()
        prepareTableView()
        loadData()
        
        refreshControl = CCRefreshControl()
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
    }
    private var pullRefreshFlag = false
    private func loadData(){
        refreshControl?.beginRefreshing()
        // 下拉刷新的代号
        var since_id = statusesList?.first?.id ?? 0
        // 上拉刷新，取得数组中最后1条数据的 id
        var max_id = 0
        if pullRefreshFlag {
            since_id = 0
            max_id = statusesList?.last?.id ?? 0
        }
        Status.loadStatus(since_id, max_id: max_id) { (statuses, error) -> () in
            
            self.refreshControl?.endRefreshing()
            if error != nil {
                SVProgressHUD.showInfoWithStatus("您的网路不给力")
                return
            }
            if statuses == nil {
                print("没有数据")
                return
            }
            if since_id > 0 {
                self.statusesList = statuses! + self.statusesList!
            } else if max_id > 0 {
                self.statusesList = self.statusesList! + statuses!
                self.pullRefreshFlag = false
                print(self.statusesList?.count)
            }else {
                self.statusesList = statuses
            }
            
        }
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        visitorView?.startAnimation()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
        rowHeightCache.removeAll()
    }
   
    // MARK: - Table view data source
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusesList?.count ?? 0
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let status = statusesList![indexPath.row]
        let ID = StatusCell.cellReuseIdentifier(status)
        let cell = tableView.dequeueReusableCellWithIdentifier(ID, forIndexPath: indexPath) as! StatusCell
        
        cell.photoDelegate = self
        cell.status = status
        
        return cell
    }
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let status = statusesList![indexPath.row]
        if rowHeightCache[status.id] != nil {
            return rowHeightCache[status.id]!
        }
        let ID = StatusCell.cellReuseIdentifier(status)
        var cls:AnyClass = StatusNormalCell.self
        if ID == CCStatusForwardCellReuseIdentifier {
            cls = StatusForwardCell.self
        }
        let cell = cls.new() as! StatusCell
        
        let height = cell.rowHeight(status)
        rowHeightCache[status.id] = height
        return height
    }
    
    // MARK: - StatusCellDelegate
    func statusCellDidSelectedPhoto(cell: StatusCell, photoIndex: Int) {
        if cell.status?.largePicURLs == nil{
            return
        }
        let vc = PhotoBrowserViewController(urls: cell.status!.largePicURLs!, index: photoIndex)
        vc.transitioningDelegate = self
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        presentViewController(vc, animated: true, completion: nil)
    }
    /**
      *  显示二维码界面
      */
    func showQRCode(){
        let sb = UIStoryboard(name: "QRCode", bundle: nil)
        presentViewController(sb.instantiateInitialViewController()!, animated: true, completion: nil)
    }
    
    /**
        设置导航条
    */
    private func setupNavigationBar(){
        if sharedUserAccount == nil {
            return
        }
       navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", highlightedImageName: nil)
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", highlightedImageName: nil)
        
        // 获取btn
        let btn = navigationItem.rightBarButtonItem!.customView as! UIButton
        btn.addTarget(self, action:"showQRCode", forControlEvents: UIControlEvents.TouchUpInside)
        let titleButton = HomeTitleButton.button(sharedUserAccount!.name!)
        titleButton.addTarget(self, action: "titleButtonClicked", forControlEvents: UIControlEvents.TouchUpInside)
        
        navigationItem.titleView = titleButton
    }
    
    let popoverAnimator = PopoverAnimator()
    func titleButtonClicked(){
        let sb = UIStoryboard(name: "FriendGroup", bundle: nil)
        let vc = sb.instantiateViewControllerWithIdentifier("FriendGroupSB")
        
        vc.transitioningDelegate = popoverAnimator
        let x = (view.bounds.width - 200) * 0.5
        popoverAnimator.presentFrame = CGRect(x: x, y: 56, width: 200, height: 300)
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        presentViewController(vc, animated: true,completion:nil)
        
    }
 
    private func prepareTableView(){
        // 注册可重用 cell
        tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: CCStatusNormalCellReuserIdentifier)
        tableView.registerClass(StatusForwardCell.self, forCellReuseIdentifier: CCStatusForwardCellReuseIdentifier)
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
    }
    private var isPresented = false
}
extension HomeTableViewController: UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning {
    
   
    // 返回提供转场 Modal 动画的对象
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        isPresented = true
        return self
    }
    
    // 返回提供转场 Dismiss 动画的对象
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        isPresented = false
        return self
    }
    
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 0.5
    }
    
    // 一旦实现，需要程序员提供动画
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        let centerP = CGPoint(x: UIScreen.mainScreen().bounds.size.width*0.5, y: UIScreen.mainScreen().bounds.size.height*0.5)
        // 1. 获取目标视图
        let viewKey = isPresented ? UITransitionContextToViewKey : UITransitionContextFromViewKey
        let targetView = transitionContext.viewForKey(viewKey)
        
        if targetView == nil {
            return
        }
        
        if isPresented {
            // 2. 添加 toView
            transitionContext.containerView()?.addSubview(targetView!)
            targetView!.alpha = 0
            targetView?.frame = CGRectZero
            targetView?.center = CGPoint(x: -800, y: -800)
            // 3. 动画
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                targetView!.alpha = 1
                targetView?.frame = UIScreen.mainScreen().bounds
                targetView?.center = centerP
                }, completion: { (_) -> Void in
                    // *** 告诉动画完成
                    transitionContext.completeTransition(true)
            })
        } else {
            // 2. 动画
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                targetView!.alpha = 0
                targetView?.bounds = CGRect(x: 0, y: 0, width: 600, height: 600)
                targetView?.center = CGPoint(x: 800, y: 800 )
                
                }, completion: { (_) -> Void in
                    targetView?.removeFromSuperview()
                    transitionContext.completeTransition(true)
            })
        }
    }
}
